package com.linkage.educloud.ah.data;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.Child;
import com.linkage.educloud.ah.bean.ClazzContact;
import com.linkage.educloud.ah.bean.ClazzGroup;
import com.linkage.educloud.ah.bean.MessItem;
import com.zzhou.common.library.util.LogUtils;
import com.zzhou.common.library.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 周振 on 2017/2/22.
 */

public class WsContentResovler {
    private static WsContentResovler instance;
    private ContentResolver mResolver;

    private WsContentResovler(Context context) {
        mResolver = context.getContentResolver();
    }

    public static WsContentResovler getResolver(Context context) {
        if (instance == null) {
            synchronized (WsContentResovler.class) {
                if (instance == null) {
                    instance = new WsContentResovler(context);
                    return instance;
                }
            }
        }
        return instance;
    }

    /**
     * 查询登录状态的用户
     *
     * @return
     */
    public AccountData getLoginAccount() {
        AccountData mAccountData = null;
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Uri.parse(Ws.AccountTable.CONTENT_URI_DEFAULT_USER + "/1"),
                    null, null, null, null);

            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                mAccountData = AccountData.fromCursor(new CursorHelper(cursor));
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return mAccountData;
    }

    /**
     * 根据账号查询用户
     *
     * @return
     */
    public AccountData getAccountByAccount(String accountName) {
        AccountData mAccountData = null;
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Ws.AccountTable.CONTENT_URI,
                    null, Ws.AccountTable.ACCOUNT_NAME + " = ?", new String[]{accountName}, null);

            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                mAccountData = AccountData.fromCursor(new CursorHelper(cursor));
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return mAccountData;
    }

    /**
     * 查询最后一次登录用户 ,最多取前3条,多余的删除
     *
     * @return
     */
    public List<AccountData> getLastAccount() {
        List<AccountData> mAccounts = null;
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Ws.AccountTable.CONTENT_URI,
                    null, null, null, Ws.AccountTable.LAST_LOGIN + " desc");
            if (cursor != null && cursor.getCount() > 0) {
                mAccounts = new ArrayList<>();
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    if (i < 3) {
                        mAccounts.add(AccountData.fromCursor(new CursorHelper(cursor)));
                    } else {
                        int id = cursor.getInt(cursor.getColumnIndex(Ws.AccountTable._ID));
                        mResolver.delete(Ws.AccountTable.CONTENT_URI, Ws.AccountTable._ID + " = " + id, null);
                    }
                    cursor.moveToNext();
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return mAccounts;
    }

    /*清除所有用户的登录状态 */
    public void clearLoginAccount() {
        ContentValues values = new ContentValues();
        values.put(Ws.AccountTable.ISLOGINING, 0);
        values.put(Ws.AccountTable.LAST_LOGIN, 0);
        mResolver.update(Ws.AccountTable.CONTENT_URI, values, null, null);
    }

    public void insertOrUpdateAccount(String accountName, AccountData data) {
        if (accountName == null) {
            return;
        }
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Ws.AccountTable.CONTENT_URI,
                    null, Ws.AccountTable.ACCOUNT_NAME + " = ?", new String[]{accountName}, null);
            if (cursor != null && cursor.getCount() > 0) {
                updateAccount(accountName, data);
            } else {
                insertAccount(accountName, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }

    public void insertAccount(String accountName, AccountData data) {
        ContentValues values = new ContentValues();
        values.put(Ws.AccountTable.ACCOUNT_NAME, accountName);
        values.put(Ws.AccountTable.PASSWORD, data.getLoginpwd());
        values.put(Ws.AccountTable.USER_NAME, data.getUserName());
        values.put(Ws.AccountTable.USER_ID, data.getUserId());
        values.put(Ws.AccountTable.PHONE, data.getPhone());
        values.put(Ws.AccountTable.USERTYPE, data.getUserType());
        values.put(Ws.AccountTable.ORGIN, data.getOrigin());
        values.put(Ws.AccountTable.GRADEID, data.getGradetype());
        values.put(Ws.AccountTable.AVATAR, data.getAvatar());
        values.put(Ws.AccountTable.CREDITSCORE, data.getCreditScore());
        values.put(Ws.AccountTable.CREDITSCORE_VILIDATE, data.getCreditScoreEndtime());
        values.put(Ws.AccountTable.ISSIGN, data.getIsSign());
        values.put(Ws.AccountTable.TOKEN, data.getToken());
        values.put(Ws.AccountTable.ISLOGINING, data.getLoginUser());
        values.put(Ws.AccountTable.LAST_LOGIN, data.getlastLoginTime());
        mResolver.insert(Ws.AccountTable.CONTENT_URI, values);
    }

    public int updateAccount(String accountName, AccountData data) {
        int rowNum = 0;
        ContentValues values = new ContentValues();
        values.put(Ws.AccountTable.ACCOUNT_NAME, accountName);
        values.put(Ws.AccountTable.PASSWORD, data.getLoginpwd());
        values.put(Ws.AccountTable.USER_NAME, data.getUserName());
        values.put(Ws.AccountTable.USER_ID, data.getUserId());
        values.put(Ws.AccountTable.PHONE, data.getPhone());
        values.put(Ws.AccountTable.USERTYPE, data.getUserType());
        values.put(Ws.AccountTable.ORGIN, data.getOrigin());
        values.put(Ws.AccountTable.GRADEID, data.getGradetype());
        values.put(Ws.AccountTable.AVATAR, data.getAvatar());
        values.put(Ws.AccountTable.CREDITSCORE, data.getCreditScore());
        values.put(Ws.AccountTable.CREDITSCORE_VILIDATE, data.getCreditScoreEndtime());
        values.put(Ws.AccountTable.ISSIGN, data.getIsSign());
        values.put(Ws.AccountTable.TOKEN, data.getToken());
        values.put(Ws.AccountTable.ISLOGINING, data.getLoginUser());
        values.put(Ws.AccountTable.LAST_LOGIN, data.getlastLoginTime());
        rowNum = mResolver.update(Ws.AccountTable.CONTENT_URI, values, Ws.AccountTable.ACCOUNT_NAME + "=?", new String[]{accountName});
        return rowNum;
    }

    public int clearAccount() {
        return mResolver.delete(Ws.AccountTable.CONTENT_URI, null, null);
    }

    public int deleteAccount(String account) {
        return mResolver.delete(Ws.AccountTable.CONTENT_URI, Ws.AccountTable.ACCOUNT_NAME + "=?", new String[]{account});
    }

    public int clearChild() {
        return mResolver.delete(Ws.ChildTable.CONTENT_URI, null, null);
    }

    public void insertChild(String accountName, Child data) {
        ContentValues values = new ContentValues();
        values.put(Ws.ChildTable.ACCOUNT_NAME, accountName);
        values.put(Ws.ChildTable.ID, data.getId());
        values.put(Ws.ChildTable.NAME, data.getName());
        values.put(Ws.ChildTable.PARENTID, data.getParentId());
        values.put(Ws.ChildTable.CLASSNAME, data.getClassname());
        values.put(Ws.ChildTable.CLASSID, data.getClassid());
        values.put(Ws.ChildTable.SCHOOL, data.getSchool());
        values.put(Ws.ChildTable.AVATAR, data.getAvatar());
        values.put(Ws.ChildTable.GRADEID, data.getGradeid());
        values.put(Ws.ChildTable.GRADENAME, data.getGradename());
        values.put(Ws.ChildTable.DEFAULTCHILD, data.getDefaultChild());
        values.put(Ws.ChildTable.REMOTEID, data.getRemoteid());
        mResolver.insert(Ws.ChildTable.CONTENT_URI, values);
    }

    public List<Child> getChild(String accountName) {
        List<Child> childList = null;
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Ws.ChildTable.CONTENT_URI,
                    null, Ws.ChildTable.ACCOUNT_NAME + " = ?", new String[]{accountName}, null);
            if (cursor != null && cursor.getCount() > 0) {
                childList = new ArrayList<>();
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    childList.add(Child.fromCursor(new CursorHelper(cursor)));
                    cursor.moveToNext();
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return childList;
    }

    public List<Child> getLastChild() {
        List<Child> mAccounts = null;
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Ws.ChildTable.CONTENT_URI,
                    null, null, null, Ws.ChildTable.ACCOUNT_NAME + " asc");
//            cursor = mResolver.query(Ws.ChildTable.CONTENT_URI,
//                    null, Ws.ChildTable.ACCOUNT_NAME + " = ?", new String[]{getLastAccount().get(0).getLoginAccount()}, null);
            if (cursor != null && cursor.getCount() > 0) {
                mAccounts = new ArrayList<>();
                cursor.moveToFirst();
                mAccounts.add(Child.fromCursor(new CursorHelper(cursor)));
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return mAccounts;
    }

    /**
     * 根据classid查询联系人集合
     *
     * @param accountName
     * @param groupId
     * @param type        用户类型
     * @return
     */
    public List<ClazzContact> getContactsById(String accountName, String groupId, int type) {
        List<ClazzContact> clazzContacts = new ArrayList<ClazzContact>();
        Cursor cursor = null;
        try {
            cursor = mResolver.query(Ws.ContactTable.CONTENT_URI, null,
                    Ws.ContactTable.ACCOUNT_NAME + " = ? and "
                            + Ws.ContactTable.GROUP_ID + " = ? and "
                            + Ws.ContactTable.TYPE + " = ?",
                    new String[]{accountName, groupId, String.valueOf(type)},//2为教师，1为家长
                    Ws.ContactTable.FIRSTNAME);
            int rows = cursor.getCount();
            cursor.moveToFirst();
            for (int i = 0; i < rows; i++) {
                clazzContacts.add(ClazzContact.fromCursor(new CursorHelper(cursor)));
                cursor.moveToNext();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return clazzContacts;
    }

    public void insertGroups(String accountName, List<ClazzGroup> groups) {
        int delete = mResolver.delete(Ws.GroupTable.CONTENT_URI, Ws.GroupTable.ACCOUNT_NAME + " = ?",
                new String[]{accountName});
        delete = mResolver.delete(Ws.ContactTable.CONTENT_URI, Ws.ContactTable.ACCOUNT_NAME + " = ?",
                new String[]{accountName});
        for (ClazzGroup group : groups) {
            ContentValues values = new ContentValues();
            values.put(Ws.GroupTable.ACCOUNT_NAME, accountName);
            values.put(Ws.GroupTable.ID, group.group_id);
            values.put(Ws.GroupTable.REMOTEID, group.remoteId);
            values.put(Ws.GroupTable.GROUP_NAME, group.group_name);
            values.put(Ws.GroupTable.GROUP_NUM, group.group_members_count);
            values.put(Ws.GroupTable.ISOPEN_SHORTDN, group.is_shortdn);
            values.put(Ws.GroupTable.DESC, group.desc);
            values.put(Ws.GroupTable.TEACHER_NUM, group.teacher_num);
            values.put(Ws.GroupTable.PARENT_NUM, group.parent_num);
            values.put(Ws.GroupTable.GROUP_TYPE, group.type);
            values.put(Ws.GroupTable.ROLE, group.role);
            values.put(Ws.GroupTable.SCHOOL, group.school_name);
            values.put(Ws.GroupTable.CLASSNAME, group.group_name);
            mResolver.insert(Ws.GroupTable.CONTENT_URI, values);
            List<ClazzContact> contacts = group.group_members;
            for (ClazzContact contact : contacts) {
                ContentValues values1 = new ContentValues();
                values1.put(Ws.ContactTable.ACCOUNT_NAME, accountName);
                values1.put(Ws.ContactTable.ID, contact.getId());
                values1.put(Ws.ContactTable.REMOTEID, contact.getRemoteId());
                values1.put(Ws.ContactTable.NAME, contact.getName());
                values1.put(Ws.ContactTable.FIRSTNAME, contact.getFirstName());
                values1.put(Ws.ContactTable.TYPE, contact.getType());
                values1.put(Ws.ContactTable.GROUP_ID, contact.getClassid());
                values1.put(Ws.ContactTable.GROUP_NAME, contact.getClassName());
                values1.put(Ws.ContactTable.AVATAR_URL, contact.getAvatar_url());
                values1.put(Ws.ContactTable.PHONE, contact.getDn());
                values1.put(Ws.ContactTable.SHORT_DN, contact.getShort_dn());
                values1.put(Ws.ContactTable.ISOPENPHONE, contact.getIsopen_phone());
                values1.put(Ws.ContactTable.CLASS_NAME, contact.getClassName());
                values1.put(Ws.ContactTable.SCHOOL_NAME, contact.getSchoolName());
                values1.put(Ws.ContactTable.STUDENT_NAME, contact.getStudentname());
                values1.put(Ws.ContactTable.STUDENT_ID, contact.getStudentid());
                values1.put(Ws.ContactTable.STUDENT_RELATIVE, contact.getStudent_relation());
                values1.put(Ws.ContactTable.INVITE, contact.getInvite());
                values1.put(Ws.ContactTable.STATUS, contact.getLogin_type());
                mResolver.insert(Ws.ContactTable.CONTENT_URI, values1);
            }
        }
    }

    /**
     * 查询所有的班级（除去自定义群组 type != 0）
     *
     * @param accountName
     * @return
     */
    public List<ClazzGroup> getGroups(String accountName) {
        Cursor cursor = null;
        List<ClazzGroup> groups = new ArrayList<ClazzGroup>();
        try {
            LogUtils.d("*******************************************" + Ws.GroupTable.ACCOUNT_NAME + " = " + accountName + " and "
                    + Ws.GroupTable.GROUP_TYPE + " = 0 and "
                    + Ws.GroupTable.ID + " > 0");
            cursor = mResolver.query(Ws.GroupTable.CONTENT_URI,
                    null,
                    Ws.GroupTable.ACCOUNT_NAME + " = ? and "
                            + Ws.GroupTable.GROUP_TYPE + " = 0 and "
                            + Ws.GroupTable.ID + " > 0",
                    new String[]{accountName},
                    null);
            int rows = cursor.getCount();
            LogUtils.d("******************************************* rows = " + cursor.getCount());
            cursor.moveToFirst();
            for (int i = 0; i < rows; i++) {
                groups.add(ClazzGroup.fromCursor(new CursorHelper(cursor)));
                cursor.moveToNext();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return groups;
    }

    public ClazzGroup getContactGroupById(String account, String groupId) {
        if (account == null) {
            return null;
        }
        Cursor cursor = null;
        ClazzGroup group = null;
        try {
            cursor = mResolver.query(Ws.GroupTable.CONTENT_URI, null, Ws.GroupTable.ACCOUNT_NAME + " =? and "
                    + Ws.GroupTable.ID + " = ?", new String[]{account, groupId}, null);
            int rowNum = cursor.getCount();
            if (rowNum > 0) {
                cursor.moveToFirst();
                group = ClazzGroup.fromCursor(new CursorHelper(cursor));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return group;
    }

    public ClazzContact getContactById(String account, String groupId, int useType) {
        if (account == null) {
            return null;
        }
        Cursor cursor = null;
        ClazzContact contact = null;
        try {
            cursor = mResolver.query(Ws.ContactTable.CONTENT_URI, null, Ws.ContactTable.ACCOUNT_NAME + " =? and "
                    + Ws.ContactTable.ID + " = ? and " + Ws.ContactTable.TYPE, new String[]{account, groupId, String.valueOf(useType)}, null);
            int rowNum = cursor.getCount();
            if (rowNum > 0) {
                cursor.moveToFirst();
                contact = ClazzContact.fromCursor(new CursorHelper(cursor));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return contact;
    }

    /**
     * 根据组id查询群组
     *
     * @param accountName
     * @param groupid
     * @return
     */
    public ClazzGroup getGroupById(String accountName, String groupid) {
        Cursor cursor = null;
        ClazzGroup group = null;
        try {
            cursor = mResolver.query(Ws.GroupTable.CONTENT_URI,
                    null,
                    Ws.GroupTable.ACCOUNT_NAME + " = ? and "
                            + Ws.GroupTable.ID + " = ?",
                    new String[]{accountName, groupid},
                    null);
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                group = ClazzGroup.fromCursor(new CursorHelper(cursor));
            } else {
                return null;
            }
        } catch (Exception e) {

        } finally {
            if (cursor != null)
                cursor.close();
        }
        return group;
    }

    public List<ClazzContact> getIMContactsForInvite(String account_name,
                                                     String userid) {
        Cursor cursor = null;
        cursor = mResolver.query(Ws.ContactTable.CONTENT_URI, null,
                Ws.ContactTable.ACCOUNT_NAME + "=? and "
                        + Ws.ContactTable.ID + "=? ", new String[]{
                        account_name, userid}, null);
        int rowNums = cursor.getCount();
        cursor.moveToFirst();
        List<ClazzContact> contacts = new ArrayList<>(
                rowNums);
        for (int i = 0; i < rowNums; i++) {
            ClazzContact user = ClazzContact
                    .fromCursor(new CursorHelper(cursor));
            contacts.add(user);
            cursor.moveToNext();
        }
        cursor.close();
        return contacts;
    }

    /**
     * 更新邀请状态
     *
     * @param accountName
     * @param id
     * @param type
     * @param invitests
     * @return
     */
    public synchronized int updateContactInvite(String accountName, long id,
                                                int type, int invitests) {
        // ClazzWorkContact contact = getContactById(accountName, id);

        if (StringUtil.isNullOrEmpty(accountName)) {
            LogUtils.d("updateContactSelectSts, accountName is null or empty, can not updte invitests!! id="
                    + id);
            return -1;
        }

        ContentValues values = new ContentValues();
        values.put(Ws.ContactTable.INVITE, invitests);

        int num = mResolver.update(Ws.ContactTable.CONTENT_URI, values,
                Ws.ContactTable.ACCOUNT_NAME + "=? and "
                        + Ws.ContactTable.TYPE + " =? and "
                        + Ws.ContactTable.ID + "=?", new String[]{
                        accountName, String.valueOf(type), String.valueOf(id)});
        return num;
    }

    /**
     * 更新是否公开手机状态
     *
     * @param accountName
     * @param id
     * @param isopen_phone
     * @param classid
     * @return
     */
    public synchronized int updateIsopen_phone(String accountName, long id,
                                               int isopen_phone, long classid) {

        ContentValues values = new ContentValues();
        values.put(Ws.ContactTable.ISOPENPHONE, isopen_phone);
        int num = mResolver.update(
                Ws.ContactTable.CONTENT_URI,
                values,
                Ws.ContactTable.ACCOUNT_NAME + "=? and "
                        + Ws.ContactTable.GROUP_ID + "=? and "
                        + Ws.ContactTable.ID + "=?",
                new String[]{accountName, String.valueOf(classid),
                        String.valueOf(id)});
        return num;
    }

    /**
     * 根据回话id，聊天类型清除所有聊天信息
     *
     * @param accountName
     * @param buddyId
     */
    public void clearIMMessages(String accountName, String buddyId) {
        mResolver.delete(
                Ws.MessageTable.CONTENT_URI,
                Ws.MessageTable.ACCOUNT_NAME + "=? AND "
                        + Ws.MessageTable.BUDDY_ID + "=?",
                new String[]{
                        accountName, buddyId});
//        String msgtype = "(" + Ws.MessageType.TYPE_MSG_TEXT + ","
//                + Ws.MessageType.TYPE_MSG_PIC + ","
//                + Ws.MessageType.TYPE_MSG_AUDIO + ")";
        mResolver.delete(
                Ws.ThreadTable.CONTENT_URI,
                Ws.ThreadTable.ACCOUNT_NAME + "=? AND "
                        + Ws.ThreadTable.BUDDY_ID + "=? AND "
                        + Ws.ThreadTable.MSG_TYPE + " in "
                        + Ws.MessageType.MSG_TYPE_CHAT,
                new String[]{
                        accountName, buddyId});
    }

    /**
     * 插入消息页面配置项
     *
     * @param accountName
     * @param items
     * @return
     */
    public void insertMessageOrderServer(String accountName, List<MessItem> items) {
        for (MessItem item : items) {
            ContentValues cv = new ContentValues();
            cv.put(Ws.MessageTable.ACCOUNT_NAME, accountName);
            cv.put(Ws.MessageTable.BUDDY_ID, item.getId());
            cv.put(Ws.MessageTable.SENDER_ID, 0);
            cv.put(Ws.MessageTable.BODY, "");
            cv.put(Ws.MessageTable.TYPE, item.getType());
            cv.put(Ws.MessageTable.OUTBOUND_STATUS, Ws.MessageType.MSG_STATUS_SENT);
            cv.put(Ws.MessageTable.IS_INBOUND, Ws.MessageType.OUTGOINT);
            cv.put(Ws.MessageTable.SENT_TIME, System.currentTimeMillis());
            cv.put(Ws.MessageTable.CHAT_TYPE, item.getChatType());
            cv.put(Ws.MessageTable.THREAD_TYPE, item.getThreadType());
            mResolver.insert(Ws.MessageTable.CONTENT_URI, cv);
        }

    }

    /**
     * 删除配置项无用配置，用于后台可能删除某个配置，页面更新
     *
     * @param accountName
     * @param ids         保留配置项的ids
     */
    public void deleteNoUseDataFromThread(String accountName, String ids) {
        mResolver.delete(Ws.ThreadTable.CONTENT_URI, Ws.ThreadTable.ACCOUNT_NAME + " = ? and "
                + Ws.ThreadTable.CHAT_TYPE + " != " + Constants.ChatType.CHAT_TYPE_SINGLE + " and "
                + Ws.ThreadTable.BUDDY_ID + " not in ( ? )", new String[]{accountName, ids}
        );
    }

    /**
     * 查询消息界面历史记录，根据threadtype进行顺序查询
     *
     * @param accountName
     */
    public Cursor queryThreadOrderByType(String accountName) {
        return mResolver.query(Ws.ThreadTable.CONTENT_URI, null, Ws.ThreadTable.ACCOUNT_NAME + " = ?",
                new String[]{accountName}, Ws.ThreadTable.THREAD_TYPE + " asc," + Ws.ThreadTable.MSG_RECEIVED_TIME + " desc");
    }

}